package org.vincen.helloworld.jaxb.basic;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * 此类演示了：
 * 1、Unmarshal an XML document into a Java content tree and access the data contained within it
 * 2、Modify a Java content tree
 * 3、Use the ObjectFactory class to create a Java content tree from scratch and then marshal it to XML data
 * 
 */
public class ModifyMain {
    
    // This sample application demonstrates how to modify a java content
    // tree and marshal it back to a xml data
    public static void main( String[] args ) {
        try {
            // A JAXBContext instance is created for handling classes generated in
            // the "org.vincen.helloworld.jaxb.tutorial" package
        	//使用xjc工具，编译po.xsd文件，生成PurchaseOrderType.java, Items.java,
        	//ObjectFactory.java, USAddress.java 4个文件
            JAXBContext jc = JAXBContext.newInstance( "org.vincen.helloworld.jaxb.basic" );
            // create an Unmarshaller
            Unmarshaller u = jc.createUnmarshaller();
            
            // unmarshal a po instance document into a tree of Java content
            // objects composed of classes from the "org.vincen.helloworld.jaxb.tutorial" package.
            JAXBElement<?> poe = 
                (JAXBElement<?>)u.unmarshal( new FileInputStream( "./src/main/java/org/vincen/helloworld/jaxb/basic/po.xml" ) );
            PurchaseOrderType po = (PurchaseOrderType)poe.getValue();

            // change the billto address
            USAddress address = po.getBillTo();
            address.setName( "John Bob" );
            address.setStreet( "242 Main Street" );
            address.setCity( "Beverly Hills" );
            address.setState( "CA" );
            address.setZip( new BigDecimal( "90210" ) );
            
            // create a Marshaller and marshal to a file
            Marshaller m = jc.createMarshaller();
            m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
            m.marshal( poe, System.out );
        } catch( JAXBException je ) {
            je.printStackTrace();
        } catch( IOException ioe ) {
            ioe.printStackTrace();
        }
    }
}
